package com.ztgf.file.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.ztgf.file.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.file.mapper.FileWatermarkMapper;
import com.ztgf.file.models.service.IFileWatermarkService;
import com.ztgf.file.models.bo.FileWatermarkSaveBO;
import com.ztgf.file.models.dto.FileWatermarkDTO;

/**
 * 水印管理控制器
 *
 * @author mxli
 * @Date 2020-07-24 14:23:21
 */
@DubboService
public class FileWatermarkServiceImpl extends ServiceImpl<FileWatermarkMapper, FileWatermarkDTO> implements IFileWatermarkService{

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(FileWatermarkSaveBO saveBO) {
        FileWatermarkDTO dto = new FileWatermarkDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public boolean save(FileWatermarkSaveBO saveBO) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("file_user_id", saveBO.getFileUserId());
        if(saveBO.getChildUserId() != null){
            wrapper.eq("child_user_id", saveBO.getChildUserId());
        }
        wrapper.eq("type", saveBO.getType());
        FileWatermarkDTO dto = this.selectOne(wrapper);

        if(dto != null){
            //修改
            BeanUtils.copyProperties(saveBO,dto);
        } else {
            //新增
            dto = new FileWatermarkDTO();
            dto.setId(ymlConfig.getPkId());
            BeanUtils.copyProperties(saveBO,dto);
        }
        this.insertOrUpdate(dto);
        if(saveBO.getIsUse() == 1){
            //修改不同类型的为0
            wrapper = new EntityWrapper();
            wrapper.eq("file_user_id", saveBO.getFileUserId());
            if(saveBO.getChildUserId() != null){
                wrapper.eq("child_user_id", saveBO.getChildUserId());
            }
            int type = saveBO.getType();
            if(type == 0){
                type = 1;
            } else {
                type = 0;
            }
            wrapper.eq("type", type);
            dto = this.selectOne(wrapper);
            if(dto != null) {
                dto.setIsUse(0);
                this.updateById(dto);
            }
        }

        return true;
    }
}
